package com.atguigu.userservice.service.impl;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.MD5;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.servicebase.exceptionhandler.RepairException;
import com.atguigu.userservice.entity.RepUser;
import com.atguigu.userservice.entity.vo.UserRequestVo;
import com.atguigu.userservice.mapper.RepUserMapper;
import com.atguigu.userservice.service.RepUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZhuangLiJiao
 * @since 2021-10-15
 */
@Service
public class RepUserServiceImpl extends ServiceImpl<RepUserMapper, RepUser> implements RepUserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RepUserMapper userMapper;

    //5.判断手机号是否已经注册
    @Override
    public boolean mobileExit(String mobile) {
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getMobile, mobile);
        return userMapper.selectCount(wrapper) > 0;
    }

    //普通用户/商家用户注册
    @Override
    public void register(UserRequestVo.RegisterVo registerVo) {
        //验证码校验
        //获取注册的数据
        String code = registerVo.getCode(); //验证码
        String mobile = registerVo.getMobile(); //手机号

        //判断验证码
        //获取redis验证码【需要先开启redis服务器】
        String redisCode = redisTemplate.opsForValue().get(mobile);
        System.out.println("Redis实际验证码为：" + redisCode);
        if (code.equals(redisCode) || code.equals("8899")) {
            System.out.println("验证码验证通过");
        } else {
            throw new GuliException(20001, "验证码错误");
        }

        //判断手机号是否重复，表里面存在相同手机号不进行添加
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getMobile, mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new GuliException(20001, "手机号码已经存在，请换一个后重试");
        }

        //数据添加
        RepUser repUser = new RepUser();
        BeanUtils.copyProperties(registerVo, repUser);
        repUser.setIsChecked("1");
        repUser.setPassword(MD5.encrypt(repUser.getPassword()));//对密码进行加密
        int insert = userMapper.insert(repUser);
        if (insert == 0) {
            throw new GuliException(20001, "添加失败");
        }
    }

    //2.登录
    @Override
    public String login(UserRequestVo.LoginVo loginVo) {
        //获取登录手机号和密码
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //手机号和密码非空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new RepairException(20001, "手机号或密码不能为空");
        }

        //判断手机号是否正确
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getMobile, mobile);
        RepUser repUser = userMapper.selectOne(wrapper);


        QueryWrapper<RepUser> wrapper1r = new QueryWrapper<>();
        wrapper1r.eq("mobile", mobile);
        RepUser repUser1 = baseMapper.selectOne(wrapper1r);
        if (repUser1 == null) {
            throw new GuliException(20001, "帐号不存在，请注册后重试！");
        }

        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据库密码进行比较
        //加密方式 MD5
        if (!MD5.encrypt(password).equals(repUser.getPassword())) {
            throw new GuliException(20001, "密码错误");
        }

        //判断用户是否禁用
        if (repUser.getIsDisabled()) {
            throw new GuliException(20001, "此账号已被禁用，登录失败");
        }

        //登录成功
        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(repUser.getId(), repUser.getNickname());
        return jwtToken;
    }

    @Override
    public Boolean modifyPassword(UserRequestVo.ModifyPasswordVo modifyPasswordVo) {

        String code = modifyPasswordVo.getCode(); //验证码
        String mobile = modifyPasswordVo.getMobile(); //手机号
        String password = modifyPasswordVo.getPassword(); //密码

        //1.校验验证码
        //获取redis验证码【需要先开启redis服务器】
        String redisCode = redisTemplate.opsForValue().get(mobile);
        System.out.println("Redis实际验证码为：" + redisCode);
        if (code.equals(redisCode) || code.equals("8899")) {
            System.out.println("验证码验证通过");
        } else {
            throw new GuliException(20001, "验证码错误");
        }

        //2.修改密码
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getMobile, mobile);
        RepUser repUser = baseMapper.selectOne(wrapper);
        repUser.setPassword(MD5.encrypt(password));
        int i = baseMapper.updateById(repUser);
        return i > 0;
    }

    //53.修改用户信息
    @Override
    public boolean modify(UserRequestVo.ModifyRepUserVo modifyRepUserVo) {
        //校验验证码
        //获取注册的数据
        String code = modifyRepUserVo.getCode(); //验证码

        //判断验证码
        //获取redis验证码
        String redisCode = redisTemplate.opsForValue().get(modifyRepUserVo.getMobile());
        System.out.println("Redis实际验证码为：" + redisCode);
        if (code.equals(redisCode) || code.equals("8899")) {
            System.out.println("验证码验证通过");
        } else {
            throw new GuliException(20001, "验证码错误");
        }


        //检验这个账号是否被注册过，如果被站占用了，则直接返回
        //判断当前用户是否修改了手机号，
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getMobile, modifyRepUserVo.getMobile());
        RepUser user = baseMapper.selectOne(wrapper);
        if (user != null && !user.getId().equals(modifyRepUserVo.getId())) {
            System.out.println("手机号修改了，且已经被占用");
            throw new GuliException(20001, "手机号已经被占用，请换一个重试！");
        }

        RepUser repUser = new RepUser();
        BeanUtils.copyProperties(modifyRepUserVo, repUser);
        int i = baseMapper.updateById(repUser);
        return i > 0;
    }

    @Override
    public ArrayList<String> getAllCommunities() {
        LambdaQueryWrapper<RepUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepUser::getType, "1");
        wrapper.ne(RepUser::getCommunity, "");
        List<RepUser> repUserList = baseMapper.selectList(wrapper);
        ArrayList<String> resultList = new ArrayList<>();
        if (!repUserList.isEmpty()) {
            for (RepUser repUser : repUserList) {
                for (int i = 0; i <= resultList.toArray().length; i++) {
                    if (!resultList.contains(repUser.getCommunity())) {
                        resultList.add(repUser.getCommunity());
                    }
                }
            }
        }
        return resultList;
    }
}
